package com.bbms.controller.index;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.bbms.entity.Result;
import com.bbms.service.UserService;
import com.bbms.util.StringUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
public class LoginController {
	
	@Resource(name="UserServiceImpl")
	UserService us;
	
	@RequestMapping(value="/", method=RequestMethod.GET)
	public String login(){
		return "login.html";
	}
	
	/**
	 * 用户登录
	 * @param account
	 * @param password
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public void userLogin(String account, String password, HttpServletRequest request, HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		JSONObject object = new JSONObject();
		System.out.println(account);
		System.out.println(password);
		System.out.println(StringUtil.isNotEmpty(account) && StringUtil.isNotEmpty(password));
		Map<?, ?> message = null;
		if (StringUtil.isNotEmpty(account) && StringUtil.isNotEmpty(password)){
			message = us.login(account, password);
			System.out.println(message.get("login").toString());
			if (Integer.parseInt(message.get("login").toString()) != 0){
				HttpSession session = request.getSession();
				session.setMaxInactiveInterval(60*60*24);
				session.setAttribute("user", account);
				session.setAttribute("authority", Integer.parseInt(message.get("authority").toString()));
				
				object.put("status", 1);
				object.put("user", account);
				object.put("authority", message.get("authority"));
				
			} else {
				object.put("status", 0);
				object.put("message", "账号或密码不正确！");
			}
		} else {
			object.put("status", 0);
			object.put("message", "账号或密码不能为空！");
		}
		out.print(object);
		out.flush();
	}
	
	
	/**
	 * 验证码验证
	 * @param validate 验证码
	 * @param request 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/validate", method=RequestMethod.POST)
	public Result validate(String validate, HttpServletRequest request){
		Result rs = new Result();
		HttpSession session=request.getSession();
		String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);     //获取生成的验证码
		if (StringUtil.isNotEmpty(validate) && validate.equals(code)){
			rs.setStatus(1);
		} else{
			rs.setStatus(0);
		}
		
		return rs;
	}
	
	private Producer captchaProducer = null;  
	  
    @Autowired  
    public void setCaptchaProducer(Producer captchaProducer) {  
        this.captchaProducer = captchaProducer;  
    }  
	
    @RequestMapping("/validate-image")
	public void getValidate(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		response.setDateHeader("Expires", 0);  
        // Set standard HTTP/1.1 no-cache headers.  
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).  
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
        // Set standard HTTP/1.0 no-cache header.  
        response.setHeader("Pragma", "no-cache");  
        // return a jpeg  
        response.setContentType("image/jpeg");  
        // create the text for the image  
        String capText = captchaProducer.createText();  
        // store the text in the session  
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
        // create the image with the text  
        BufferedImage bi = captchaProducer.createImage(capText);  
        ServletOutputStream out = response.getOutputStream();  
        // write the data out  
        ImageIO.write(bi, "jpg", out);  
        try {  
            out.flush();  
        } finally {  
            out.close();  
        }  
	}
}
